<?php
/**
 * 订单
 * User: Tsang
 * Date: 2017/10/30 15:50
 *
 */

namespace app\admin\controller;


use app\api\controller\Pay;
use think\Db;

class Order extends Common
{

    /**
     * 订单列表
     */
    public function index(){
        $where = 'order_id > 0';
        $ordere_sn = input('sn/s');
        if(!empty($ordere_sn)){
            $where .= ' and order_sn = "'.$ordere_sn.'"';
        }
        $start_time = input('start/s');
        $start_time = strtotime($start_time);
        if(!empty($start_time)){
            $where .= ' and create_time > "'.$start_time.'"';
        }
        $end_time = input('end/s');
        $end_time = strtotime($end_time);
        if(!empty($end_time)){
            $where .= ' and create_time < "'.$end_time.'"';
        }
        $status = input('status/s');
        if($status != ''){
            if(!in_array($status,array(ORDER_STATUS_NOPAY,ORDER_STATUS_PAID,ORDER_STATUS_SENT,ORDER_STATUS_SUCCESS))) $this->error('非法操作');
            $where .= ' and order_state = "'.$status.'"';
        }

        $list = db('order')->where($where)->order('order_id desc')->paginate(20)->each(function($item,$key){
            $order_product = db('order_product')->where(array('order_id'=>$item['order_id']))->field('product_id,count,product_name')->select();

            foreach ($order_product as $key => $value) {
                $brand_id = db('goods')->where(array('id'=>$value['product_id']))->column('brand_id');
                if(!empty($brand_id[0])){
                    $brand_name = db('goods_brand')->where(array('id'=>$brand_id[0]))->column('name');
                    if(!empty($brand_name[0])){
                        $order_product[$key]['bname'] = $brand_name[0];
                    }else{
                        $order_product[$key]['bname'] = '';
                    }
                }else{
                    $order_product[$key]['bname'] = '';
                }
            }

            $item['order_goods'] = $order_product;
            return $item;
        });
        $this->assign('list',$list);
        return $this->fetch();
    }


    /**
     * 订单详情
     */
    public function det(){
        $id = input('id/d');
        $data = db('order')->where(['order_id' => $id])->find();
        if(!$data) $this->error('找不到订单');
        $data['address'] = object_to_array(json_decode($data['address']));
        $data['remarks'] = htmlspecialchars_decode($data['remarks']);
        $data['goods'] = db('order_product')->where(['order_id' =>$data['order_id']])->select();
        $data['refund'] = array();
        if(!empty($data['refund_id'])){
            $refund_ids = explode(',', $data['refund_id']);

            //订单全部退款
            $data['refund'] = db('refund')->where(['refund_id' => ['in',$refund_ids],'order_id' => $data['order_id'],'goods_id'=>'0'])->find();

            //单个商品退款
            $data['refund_goods'] = db('refund')->where(['refund_id' => ['in',$refund_ids],'order_id' => $data['order_id'],'goods_id'=>['neq','0']])->select();

            if(!empty($data['refund']['images'])){
                $data['refund']['images'] = json_decode($data['refund']['images']);
                foreach($data['refund']['images'] as &$fg){
                    $fg = __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$fg);
                }
            }

            if(!empty($data['refund']['reason'])){
                $data['refund']['reason'] = htmlspecialchars_decode($data['refund']['reason']);
            }

        }

        $data['goods'] = db('order_product')->where(['order_id' => $data['order_id']])->select();
        

        foreach($data['goods'] as &$og){
            if(!empty($og['product_img'])){
                $og['product_img'] = __ROOT__ . '/static/uploads'.str_replace('\\',"/",$og['product_img']);
            }
        }
        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
    *  pdf订单
    */
    public function pdf_order(){
        $html = input('html');
        $id = input('id');
        $order_result = db('order')->where(['order_id'=>$id])->find();
        $member = object_to_array(json_decode($order_result['address']));
        //$member = db('member')->where(['id'=>$order_result['user_id']])->field('nickname,mobile')->find();
        $order_result['nickname'] = $member['name'];
        $order_result['mobile'] = $member['mobile'];
        $order_result['sent_time'] = date("Y/m/d",$order_result['sent_time']);
        $order_result['address'] = object_to_array(json_decode($order_result['address']));

        //订单商品
        $order_product = db('order_product')->where(['order_id'=>$id])->select();

        foreach ($order_product as $key => &$value) {
            $value['product_img'] = __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$value['product_img']);
            $goods_result = db('goods')->where(['id'=>$value['product_id']])->field('goods_sn')->find();
            $value['goods_sn'] = $goods_result['goods_sn'];
        }

        if(request()->isAjax()){
            $html = str_replace("点击修改内容","",$html);

            $result = db('order')->where(array('order_id'=>$id))->update(['pdf_html'=>$html]);
            if(!$result)return $this->error('保存失败');
            $this->success('保存成功');
        }

        $this->assign('pdf_html',$order_result['pdf_html']);
        $this->assign('order_result',$order_result);
        $this->assign('order_product',$order_product);

        $this->assign('id',$id);
        return $this->fetch();
    }

    /**
    *   下载pdf
    */
    public function down_pdf(){
        $html = input('html');
        $id = input('id');
        require_once '../vendor/mpdf/mpdf/mpdf.php';

        $order_result = db('order')->where(['order_id'=>$id])->field('pdf_html,order_sn')->find();
        if(empty($order_result['pdf_html']))$this->error('请先保存订单模板');
        $html = $order_result['pdf_html'];

        //设置中文编码
        $mpdf=new \mPDF('zh-cn','A3', 0, '宋体', 0, 0);

        $style = ".ncap-order-style { width: 1000px; margin: 0 auto; }
            .ncap-order-flow { background-color: #F5F5F5; padding: 10px 0; margin-bottom: 60px; border-radius: 5px; position: relative; z-index: 1; }
            .ncap-order-flow ol { font-size: 0; }
            .ncap-order-flow li { font-size: 12px; text-align: center; vertical-align: top; display: inline-block; position: relative; z-index: 1; }
            .ncap-order-flow .num5 li { width: 20%; }
            .ncap-order-flow .num3 li { width: 33.333%; }
            .ncap-order-flow li i { font-size: 18px; color: #D7D7D7; position: absolute; z-index: 1; right: -8px; top: 2px; }
            .ncap-order-flow li h5 { font-size: 16px; font-weight: normal; line-height: 20px; height: 20px; }
            .ncap-order-flow li time { font-family: Gotham, \"Helvetica Neue\", Helvetica, Arial, sans-serif; font-size: 11px; color: #777; background-color: #FFF; line-height: 16px; text-align: center; display: none; width: 140px; height: 16px; margin-left: -70px; border: dotted 1px #D6D6D6; border-radius: 10px; position: absolute; z-index: 1; bottom: -20px; left: 50%; }
            .ncap-order-flow li.current h5 { color: #2cbca3; font-weight: 600; }
            .ncap-order-flow li.current i { color: #2cbca3; }
            .ncap-order-flow li.current time { display: block; }
            /*线下团订单详情页面的特殊性*/
            .ncap-order-flow .code-list { font-size: 12px; background-color: #FFF; text-align: left; width: 370px; padding: 9px 0 9px 9px; margin: 3px 0 0 5px; border: dotted 1px #D6D6D6; border-radius: 10px; position: relative; z-index: 1; box-shadow: 3px 3px 0 rgba(153,153,153,0.05); }
            .ncap-order-flow .code-list #codeList { max-height: 75px; position: relative; z-index: auto; overflow: hidden; }
            .ncap-order-flow .code-list ul { width: 96%; }
            .ncap-order-flow .code-list li { color: #999; line-height: 20px; background-color: #FCFCFC; text-align: left; display: block; width: 100%; clear: both; margin-top: 5px; }
            .ncap-order-flow .code-list li:hover { background-color: #FFF; box-shadow: 0 0 5px rgba(204,204,204,0.75); }
            .ncap-order-flow .code-list li strong { font-family: Tahoma; font-size: 12px; font-weight: 600; color: #2cbca3; margin: 0 20px 0 5px; }
            .ncap-order-flow .code-list li.used { color: #F90; background-color: transparent; box-shadow: none; }
            .ncap-order-flow .code-list li.used strong { color: #999; }
            .ncap-order-details { border: solid 1px #2cbca3; position: relative; z-index: 1; }
            .ncap-order-details .tabs-nav { font-size: 0; position: absolute; z-index: 1; top: -30px; left: 20px; }
            .ncap-order-details .tabs-nav li { font-size: 12px; display: inline-block; margin-right: 5px; }
            .ncap-order-details .tabs-nav li a { line-height: 20px; color: #777; background-color: #F5F5F5; display: block; height: 20px; padding: 4px 19px; border-style: solid; border-width: 1px; border-color: #F5F5F5 #F5F5F5 #2cbca3 #F5F5F5; border-radius: 4px 4px 0 0; }
            .ncap-order-details .tabs-nav li.current a { background-color: #FFF; color: #2cbca3; font-weight: 600; border-color: #2cbca3 #2cbca3 #FFFFFF #2cbca3; }
            .ncap-order-details .tabs-panels { padding: 9px 19px; }
            .ncap-order-details h4 { font-size: 12px; line-height: 20px; font-weight: 600; color: #333; height: 20px; margin-bottom: 8px; }
            .ncap-order-details .misc-info,
            .ncap-order-details .addr-note,
            .ncap-order-details .contact-info { padding-bottom: 10px; /*margin-bottom: 10px; border-bottom: solid 1px #E6E6E6;*/ }
            .ncap-order-details .tabs-hide { display: none; }
            .ncap-order-details table {width: 100%; }
            .ncap-order-details table tr th, table tr td{border: solid 1px #D7D7D7; text-align: center; min-height: 20px; padding: 9px; }
            .ncap-order-details table thead th { background-color: #edfbf8; border: solid 1px #D7D7D7; }
            .ncap-order-details table .goods-thumb { width: 30px; height: 30px; }
            .ncap-order-details table .goods-thumb a { line-height: 0; background-color: #FFF; text-align: center; vertical-align: middle; display: table-cell; *display: block;
                width: 30px; height: 30px; overflow: hidden; }
            .ncap-order-details table .goods-thumb a img { max-width: 30px; max-height: 30px; margin-top:expression(30-this.height/2);
            }
            .ncap-order-details .total-amount { text-align: right; padding: 10px 0; }
            .ncap-order-details .total-amount h3 { font-size: 14px; font-weight: normal; color: #777; line-height: 24px; }
            .ncap-order-details .total-amount h3 strong { font-size: 20px; color: #ff3300; }
            .ncap-order-details .total-amount h4 { color: #999; font-size: 12px; font-weight: normal; line-height: 20px; }
            .ncap-order-details .total-amount h5 { }
            ";

        //接入style
        $mpdf->WriteHTML($style,1);
        $mpdf->WriteHTML($html,0,false);
        $mpdf->Output(''.$order_result['order_sn'].'.pdf',true);
        exit;
    }

    /**
     * 发货
     */
    public function sent(){
        $id = input('id/d');
        $m_order = db('order');
        $order = $m_order->where(['order_id' => $id])->find();
        if(!$order){
            echo json_encode(['msg' => '找不到订单','error' => -1]);
            exit;
        }
        if($order['order_state'] != ORDER_STATUS_PAID){
            echo json_encode(['msg' => '订单不是已付款状态','error' => -1]);
            exit;
        }
        if($order['refund_id'] > 0){
            echo json_encode(['msg' => '订单退款中','error' => -1]);
            exit;
        }
        $express_type = input('express_type/s');
        if(empty($express_type)){
            echo json_encode(['msg' => '快递方式不能为空','error' => -1]);
            exit;
        }
        $express_num = input('express_num/s');
        if(empty($express_num)) {
            echo json_encode(['msg' => '快递单号不能为空','error' => -1]);
            exit;
        }
        $data = array(
            'order_state' => ORDER_STATUS_SENT,
            'sent_time' => TIMESTAMP,
            'express_type' => htmlspecialchars($express_type),
            'express_num' => htmlspecialchars($express_num),
        );
        if($m_order->where(['order_id' => $id])->update($data) === false){
            echo json_encode(['msg' => '操作失败','error' => -1]);
        }else{
            echo json_encode(['error' => 0]);
        }
    }

    /**
     * 取消订单
     */
    public function cancel(){
        $id = input('id/d');
        $m_order = db('order');
        $order = $m_order->where(['order_id' => $id])->find();
        if(!$order) return array('message' => '找不到订单');
        if($order['order_state'] != ORDER_STATUS_NOPAY) return array('message' => '该订单不支持此操作');
        $order_goods = db('order_product')->where(['order_id' => $order['order_id']])->select();

        Db::startTrans();
        try{

            $m_order->where(['order_id' => $id])->update(['order_state' => ORDER_STATUS_CLOSE]);

            //加回库存
            $m_goods_option_value = db('goods_option_value');
            foreach($order_goods as $g){
                $m_goods_option_value->where(['goodsid' => $g['product_id'],'spec_name' => $g['spec']])->setInc('stock',$g['count']);
            }

            if($order['voucher_id'] > 0){
                $m_voucher = db('myvoucher');
                $voucher = $m_voucher->where(['id' => $order['voucher_id']])->find();
                if($voucher && $voucher['end_time'] > TIMESTAMP){
                    $m_voucher->where(['id' => $order['voucher_id']])->update(['status' => 0]);
                }
            }

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }

        $this->success("操作成功",url('order/index'));
    }


    /**
     * 退款列表
     */
    public function refund(){
        $where = '';

        $start_time = input('start/s');
        if(!empty($start_time)){
            $start_time = strtotime($start_time);
            $where .= ' r.create_time > "'.$start_time.'"';
        }
        $end_time = input('end/s');
        if(!empty($end_time)){
            $end_time = strtotime($end_time);
            $where .= ' and r.create_time < "'.$end_time.'"';
        }

        $refund = db('refund')->alias('r')
            ->join('order o','o.order_id = r.order_id')
            ->where($where)
            ->order('r.refund_id desc')
            ->field('r.is_invoice,r.refund_id,r.refund_sn,r.money,r.create_time,o.order_sn,o.order_id,r.status')
            ->paginate(20);
        $this->assign('list',$refund);
        return $this->fetch();
    }

    /**
     * 整个订单退款详情
     */
    public function refund_det(){
        $id = input('id/d');
        $m_refund = db('refund');
        $data = $m_refund->alias('r')
            ->join('order o','o.order_id = r.order_id')
            ->where(['r.refund_id' => $id])
            ->order('r.refund_id desc')
            ->find();
        $order_product_result = db('order_product')->where(['order_id'=>$data['order_id']])->field('product_id')->select();
        if(!$data) $this->error('找不到');
        $data['reason'] = htmlspecialchars_decode($data['reason']);
        $data['des'] = htmlspecialchars_decode($data['des']);
        $data['address'] = json_decode($data['address'],true);

        //查询出单独退商品的退货订单
        $refund_ids = explode(',', $data['refund_id']); 

        if($data['goods_id'] == '0'){
            //查询整个订单退货
            $refund_goods_result = db('refund')->where(['refund_id'=>['in',$refund_ids],'goods_id'=>['neq','0']])->field('goods_id')->select();
            $refund_goods_ids = array_column($refund_goods_result, 'goods_id');

            //查询出订单的商品
            $refund_product_ids = array_column($order_product_result, 'product_id');

            //删除掉单独退商品的订单，剩余的就是订单退货
            $goods_ids = array_diff($refund_product_ids, $refund_goods_ids);

            //查询该退货订单有是退什么商品
            $order_product_where['order_id'] = $data['order_id'];

            if(!empty($goods_ids)){
                $order_product_where['product_id'] = array('in',$goods_ids);
            }
        }else{
            //查询单个商品退货
            $order_product_where['order_id'] = $data['order_id'];

            $order_product_where['product_id'] = $data['goods_id'];
        }
        
        $data['goods'] = db('order_product')->where($order_product_where)->select();
        
        if(!empty($data['goods'])){
            foreach($data['goods'] as &$og){
                if(!empty($og['product_img'])){
                    $og['product_img'] = __ROOT__ . '/static/uploads'.str_replace('\\',"/",$og['product_img']);
                }
            }
        }


        $action='';
        $admin_refund = db('order_admin_refund')->where(array('order'=>$data['order_id'],'status'=>'1','refund_id'=>$id))->find();
        $admin_name = db('admin')->where(array('id'=>$admin_refund['aid']))->field('account')->find();
        
        //查询有多少个管理员，有一个则直接让admin账号操作退款，有多个则需要其他管理审核通过以后admin账号才能操作退款
        $admin_count = db('admin')->count('id');

        if($admin_count > 1 && empty($admin_refund) && $this->admin_info['role_id'] != 1){
            //管理员审核
            $action=url('Order/admin_refund_det',array('refund_id'=>$id));
        }

        if ($this->request->isPost()) {
            if (intval($data['status']) == -1 || intval($data['status']) == 2) $this->error('该订单已审核过');

            if($admin_count > 1){
                if(empty($admin_refund))$this->error('该订单,其他管理员还没有做退款审核!');
            }

            $status = input('status/d');
            if (!in_array($status, array(-1, 1, 2))) $this->error('操作状态失败');
            Db::startTrans();
            try {
                $m_refund->where(['refund_id' => $id])->update(['status' => $status,'audit_time'  => TIMESTAMP]);

                if ($status == 2) {
                    $result = (new Pay($this->request))->wechat_refund($data['order_id'],$data['refund_sn']);
                    if(!$result) throw new \Exception('退款失败');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->redirect(url('order/refund'));
        }
        $this->assign('data',$data);
        $this->assign('action',$action);
        $this->assign('admin_refund',$admin_refund);
        $this->assign('admin_name',$admin_name['account']);
        $this->assign('admin_account',$this->admin_info['account']);
        $this->assign('admin_count',$admin_count);
        return $this->fetch();
    }

    /**
    *管理员审核
    */
    public function admin_refund_det(){
        $refund_id = input('refund_id/d');
        $is_invoice = input('is_invoice');
        $refund = db('refund')->where(array('refund_id'=>$refund_id))->field('order_id')->find();

        $data['order'] = $refund['order_id'];
        $data['aid'] = $this->admin_info['id'];
        $data['refund_id'] = $refund_id;
        $data['status'] = '1';
        $order_admin_refund = db('order_admin_refund')->where(array('order'=>$data['order'],'refund_id'=>$refund_id))->find();
        if(!empty($order_admin_refund))$this->error('审核失败');
        $result = db('order_admin_refund')->insert($data);
        if(!$result)$this->error('审核失败');

        $status = input('status/d');
        if (!in_array($status, array(-1, 1, 2))) $this->error('操作状态失败');
        db('refund')->where(['refund_id' => $refund_id])->update(['status' => $status,'audit_time'  => TIMESTAMP,'is_invoice'=>$is_invoice]);

        $this->success('审核通过',url('Order/index'));
    }


    /**
    *订单统计
    */
    public function order_statistics(){
        $order_status = input('order_status');
        $start_time = input('start/s');
        $start_time_stamp = strtotime($start_time);
        $order_string = '';
        if(!empty($start_time)){
            $order_string .= 'and go.create_time > "'.$start_time_stamp.'"';
        }
        $end_time = input('end/s');
        $end_time_stamp = strtotime($end_time);
        if(!empty($end_time)){
            $order_string .= ' and go.create_time < "'.$end_time_stamp.'"';
        }

        switch ($order_status) {
            case '-1':
                //取消订单
                $order_string .= " and go.order_state = '-1'";
                break;
            case '0':
                //待付款
                $order_string .= " and go.order_state = '0'";
                break;
            case '1':
                //已付款
                $order_string .= " and go.order_state = '1'";
                break;
            case '2':
                //已发货
                $order_string .= " and go.order_state = '2'";
                break;
            case '3':
                //已完成
                $order_string .= " and go.order_state = '3'";
                break;
            case '4':
                //已退货
                $order_string .= " and go.refund_id != '0'";
                break;
        }

        //所有订单按品牌查询
        $order_all = db()->query("select count(god.count_order) as count_order_id,god.brand_name,god.total_price_sum from (select op.order_id as count_order,(select `name` from gas_goods_brand where id = gg.brand_id) as brand_name,gg.brand_id,go.order_state,go.refund_id,sum(go.total_price) as total_price_sum from gas_order as go left join gas_order_product as op on go.order_id = op.order_id left join gas_goods as gg on gg.id = op.product_id where gg.brand_id != '0' ".$order_string." group by count_order) as god group by god.brand_id");

        $this->assign('order_all',$order_all);
        $this->assign('order_status',$order_status);
        return $this->fetch();
    }


}